#!/bin/bash
#list the pid and cmd of all dbus services
#https://blog.zeerd.com/dbus-show-detail-namelist/

AWK="awk"
TR="tr"

function colorEcho {
    case "$1" in
    -g|--green)
        echo -e "\033[1;32m$2\033[0m";;
    -r|--red)
        echo -e "\033[1;31m$2\033[0m";;
    -y|--yellow)
        echo -e "\033[1;33m$2\033[0m";;
    esac
}



ADDRESS=
SESSION=
SYSTEM=

#Phrase options
opts=$(getopt -o "a:h" --long  "help,address:,session,system" -n "$0" -- "$@")
if [ $? -ne 0 ]; then
    colorEcho -r "Phrase opts error"
    #usage
    exit 4
fi

eval set -- $opts


while [ -n "$1" ]; do
    case "$1" in
    -a|--address)
        ADDRESS="--bus=$2"
        shift 2;;
    --session)
        SESSION="--session"
        shift ;;
    --system)
        SYSTEM="--system"
        shift ;;
    --)
        shift
        break;;
    *)
        colorEcho -r "Unknown opt:$1"
        #usage
        exit 3;;
    esac
done



echo checking...
echo -e "srv-name/sender-id\tpid\tprocess-cmd"
lists=$(dbus-send \
            $ADDRESS $SESSION $SYSTEM \
            --dest=org.freedesktop.DBus \
            --type=method_call \
            --print-reply \
            /org/freedesktop/DBus org.freedesktop.DBus.ListNames \
      | $AWK '{if($1=="string") {n=$2;gsub("\"","",n);print n}}')
      #| $AWK '{if($1=="string" && $2!~/:[0-9.]+/) {n=$2;gsub("\"","",n);print n}}')

for i in $lists
do
        name="string:$i"
        #echo $name
        PID=$(dbus-send \
                    $ADDRESS $SESSION $SYSTEM \
                    --print-reply \
                    --dest=org.freedesktop.DBus \
                    / \
                    org.freedesktop.DBus.GetConnectionUnixProcessID $name \
            2>&1 \
            | $AWK '{if($1=="uint32")print $2}')
        #echo $PID
        if [ "x$PID" != "x" ] ; then
                echo -ne $i "\t" $PID "\t"
                cat  /proc/$PID/cmdline | $TR "\0" " "
                echo
        fi
done | sort

